<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="24">
        <div>
          <el-input
            placeholder="输入关键字进行过滤"
            v-model="filterText">
          </el-input>
          <div class="treeArea">
            <el-tree ref='tree'
                     v-loading="loading"
                     :data="treeData"
                     label="name"
                     show-checkbox
                     @check-change="checkChange"
                     :props="defaultProps"
                     :expand-on-click-node='false'
                     :filter-node-method="filterNode"
                      node-key="id"
                     :check-strictly="true"
                     :default-checked-keys="treeDataSelect"

                     class="filter-tree"
                     :highlight-current='true'
                     :default-expand-all='true'
                     @check="clickDeal"></el-tree>
          </div>
          <el-row :gutter="5" style="margin-right: 12px;">
            <el-col style="text-align: center; border-top:1px solid #e6e6e6; padding-top:20px; margin-top:10px;">
              <el-button size="small" class="filter-item" type="primary" @click="saveData" v-loading="btnLoading">保 存</el-button>
              <el-button size="small" class="filter-item" type="primary" @click="closeSelf">关 闭</el-button>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <!--<el-col :span="12"></el-col>-->
    </el-row>
  </div>
</template>

<script>
import {
  selectMenuTree,
  hasSelectPri,
  batchInsertItemByParent
} from '@/api/systemManage/roleManagementRoleEdit'
export default {
  name: 'powerRole',
  components: {},
  props: ['powerRoleData'],
  data() {
    return {
      loading: false,
      btnLoading: false,
      treeData: [],
      treeDataSelect: [],
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      oldMenuIdArr: [],
      listQuery: {
        condition: {
        },
        fields: [
        ],
        sort: [{
          direction: 'ASC',
          property: 'roleId'
        }]
      },
      rowId: ''
    }
  },
  created() {
    this.loading = true
    selectMenuTree({ orgId: this.powerRoleData.id, userId: this.$store.getters.userid, type: '0,3' }).then(response => {
      this.treeData = response.data.data
      this.loading = false
    })

    this.listQuery.roleId = this.powerRoleData.id
    // var uu=[]
    // this.treeDataSelect=[]
    hasSelectPri(this.listQuery).then(response => {
      response.data.data.records.forEach((item, index) => {
        this.treeDataSelect.push(item.priId)
      })
      // this.treeDataSelect=uu
      // alert(this.treeDataSelect)
      // /////////////////////////////////////////////
      // 以下部分是回显时,将只有部分选择子节点的父节点剔除

      // this.$refs.tree.setCheckedKeys(this.treeDataSelect,true)
      /*
      setTimeout(function () {
           this.treeDataSelect.forEach((value)=>{
//1. 勾选节点的 key 或者 data 2. boolean 类型，节点是否选中 3. boolean 类型，是否设置子节点 ，默认为 false）如果全部选中setCheckedKeys
              that.$refs.tree.setChecked(value,true,false)
           })
      },500);*/

      // /////////////////////////////////////////////
    })
  },
  methods: {
    checkChange(data, checked, indeterminate) {
      /*
      var treeData = data
      var keys = this.$refs.tree.getCheckedKeys()
     // alert(JSON.stringify(data))
     // alert(keys)
      if (treeData.children.length > 0) {
        if (checked) {
          // 添加操作
          treeData.children.forEach((item, index) => {
            if (keys.indexOf(item.id) === -1) {
              keys.push(item.id)
            }
          })
          this.$refs.tree.setCheckedKeys(keys)
        } else {
          // 删除操作
          treeData.children.forEach((item, index) => {
            if (keys.indexOf(item.id) >= -1) {
              keys.indexOf(item.id) == -1
            }
          })
          this.$refs.tree.setCheckedKeys(keys)
        }
      }
      */
    },
    hasSelectPriData() {

    },
    filterNode(value, data) {
    console.log('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')
    console.log(data)
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    editTree() {
      selectMenuTree({ orgId: this.powerRoleData.id, userId: this.$store.getters.userid }).then(response => {
        this.treeData = response.data.data
      })
    },
    saveData() {
      this.btnLoading = true
      const insertArr = []
      //  const checkedKeys = this.$refs.tree.getCheckedKeys()
      //  console.log(checkedKeys)
      // ///////////////////////////////////////

      // var arr1  = this.$refs.tree.getHalfCheckedKeys()
      // var array = arr.concat(arr1);

      var arr = this.$refs.tree.getCheckedKeys()
      var array = []
      for (var i = 0; i < arr.length; i++) {
        this.fun(arr[i], this.treeData, array)
      }

      // ///////////////////////////////////////
      for (const temp of array) {
        const input = {}
        input.priId = temp
        insertArr.push(input)
      }

      var search = {
        insertArr: insertArr,
        roleId: this.powerRoleData.id
      }
      batchInsertItemByParent(search).then(response => {
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
        this.btnLoading = false
        this.$emit('changeCloseDialog')
        // this.$router.push({ name: 'roleManagement' })
      })
    },
    closeSelf() {
      this.$emit('changeCloseDialog')
      // this.$router.push({ name: 'roleManagement' })
    },
    fun(value, data, arr) { // 通过查询父节点下是否右子节点 将半选状态的父节点加入数组中
      for (var i = 0; i < data.length; i++) {
        var mod = data[i]
        if (mod.id == value) {
          if (this.noRepeat(arr, mod.id)) {
            arr.push(mod.id)
          }
          return true
        } else {
          if (mod.children) {
            var bool = this.fun(value, mod.children, arr)
            if (bool) {
              if (this.noRepeat(arr, mod.id)) {
                arr.push(mod.id)
              }
              return true
            }
          }
        }
      }
      return false
    },
    noRepeat(arr, value) { // id去重
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] == value) {
          return false
        }
      }
      return true
    },
    fun1(value, data, arr) {
      for (var i = 0; i < data.length; i++) {
        var mod = data[i]
        if (mod.id == value) {
          if (mod.children.length == 0) {
            arr.push(mod.id)
            return true
          }
          return true
        } else {
          // mod.children.id
          if (mod.children.length != 0) {
            this.fun1(value, mod.children, arr)
          }
        }
      }
      return true
    },
    updated() {
      // 给多选树设置默认值
      this.$refs.tree.setCheckedKeys(this.treeDataSelect)
    },
    clickDeal(currentObj, treeStatus) {
      this.clickCheck(currentObj, treeStatus, this.$refs.tree)
    },

    /**
             * 树形菜单复选框父子节点不关联实现父子节点联动回显
             *
             * @see selectedParent - 处理父节点为选中
             * @see uniteChildSame - 处理子节点为相同的勾选状态
             * @see removeParent   - 子节点全没选中取消父级的选中状态
             *
             * @param {Object} currentObj - 当前勾选节点的对象
             * @param {Object} treeStatus - 树目前的选中状态对象
             * @param {Object} ref - this.$refs.xxx
             **/
    clickCheck(currentObj, treeStatus, ref) {
      // 用于：父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
      // alert(JSON.stringify(treeStatus.checkedKeys))
      let selected = treeStatus.checkedKeys.indexOf(currentObj.id) // -1未选中

      // 选中
      if (selected !== -1) {
        // 子节点只要被选中父节点就被选中
        this.selectedParent(currentObj, ref)
        // 统一处理子节点为相同的勾选状态
        this.uniteChildSame(currentObj, true, ref)
      } else {
        // 取消子节点的选中状态触发
        // alert(JSON.stringify(currentObj.parent_id))
        if (currentObj.parent_id !== '****') {
          this.removeParent(currentObj, ref)
        }

        // 未选中 处理子节点全部未选中
        if (currentObj.children.length !== 0) {
          this.uniteChildSame(currentObj, false, ref)
        }
      }
    },

    /**   统一处理子节点为相同的勾选状态  **/
    uniteChildSame(treeList, isSelected, ref) {
      let treeListData = treeList.children
      let len = treeListData.length

      ref.setChecked(treeList.id, isSelected)

      for (let i = 0; i < len; i++) {
        this.uniteChildSame(treeListData[i], isSelected, ref)
      }
    },

    /**    统一处理父节点为选中    **/
    selectedParent(currentObj, ref) {
      let currentNode = ref.getNode(currentObj)
      if (currentNode.parent.key !== undefined) {
        ref.setChecked(currentNode.parent, true)
        return this.selectedParent(currentNode.parent, ref)
      }
    },

    /**    子节点全没选中取消父级的选中状态   **/
    removeParent(currentObj, ref) {
      let a = 0
      let b = 0
      let currentNode = ref.getNode(currentObj)
      if (currentNode.parent !== null) {
        if (currentNode.parent.key !== undefined) {
          ref.setChecked(currentNode.parent, true) // 根节点
          this.removeParent(currentNode.parent, ref) // 递归判断子节点
        }
      }

      // 不为0表示为父节点
      if (currentNode.childNodes.length !== 0) {
        // 循环判断父节点下的子节点
        for (let i = 0; i < currentNode.childNodes.length; i++) {
          // 判断父节点下的子节点是否全为false
          if (currentNode.childNodes[i].checked === false) {
            ++a

            // a === currentNode.childNodes.length 表明子节点全为false
            if (a === currentNode.childNodes.length) {
              // 等于 undefined 跳过,不等于继续执行
              if (currentNode.childNodes[i].parent.key !== undefined) {
                ref.setChecked(currentNode.childNodes[i].parent, false) // 父元素设置为false
                // 循环上级父节点下的子节点
                for (let i = 0; i < currentNode.parent.childNodes.length; i++) {
                  // 判断父节点下的子节点是否全为false
                  if (currentNode.parent.childNodes[i].checked === false) {
                    ++b

                    // b === currentNode.parent.childNodes.length 表明子节点全为false
                    if (b === currentNode.parent.childNodes.length) {
                      ref.setChecked(currentNode.parent.key, false) // 父元素设置为false
                      return this.removeParent(currentNode.parent, ref) // 继续递归循环判断
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

  },
  watch: {
    filterText(val) {
      console.log('aaaaaaaaaaaaaaaaaaaaaaaaaa')
      console.log('val')
      this.$refs.tree.filter(val)
    }
  }
}
</script>

<style scoped>
.treeArea {
  max-height: 45vh;
  overflow-y: auto;
  margin-top: 10px;
}
</style>
